<template>
	<view class="bottomBar" style="padding-bottom: 100rpx;">
		<view class="createCardWp">
			<view class="swiper-top">
				<swiper class="swiper" circular :current='acvtiveIndex' :indicator-dots="indicatorDots"
					:autoplay="autoplay" :interval="interval" :duration="1000" @change="swiperChange">
					<swiper-item class="item-swiper">
						<defaultCard :userInfo="formData"></defaultCard>
					</swiper-item>
					<swiper-item class="item-swiper">
						<card-style1 :userInfo="formData"></card-style1>
					</swiper-item>
					<swiper-item class="item-swiper">
						<card-style2 :userInfo="formData"></card-style2>
					</swiper-item>
					<swiper-item class="item-swiper">
						<card-style4 :userInfo="formData"></card-style4>
					</swiper-item>
					<swiper-item class="item-swiper">
						<card-style5 :userInfo="formData"></card-style5>
					</swiper-item>
					<swiper-item class="item-swiper">
						<defaultCard :userInfo="formData" bgStyle="2"></defaultCard>
					</swiper-item>
					<swiper-item class="item-swiper">
						<card-style6 :userInfo="formData"></card-style6>
					</swiper-item>
					<swiper-item class="item-swiper">
						<defaultCard :userInfo="formData" bgStyle="3"></defaultCard>
					</swiper-item>
				</swiper>
			</view>
			<view class="cardFrom">
				<view class="position">
					<view class="titleText">
						名片样式
					</view>
					<view class="img-list-box">
						<view class="img-list-item" v-for="(item,index) in CardStyleList" :key="index"
							@click="changeCardStyle(item,index)">
							<view class="img-list-mask" v-if="acvtiveIndex==index">
								<img src="https://file.casugn.com/storecompcard//vDMG9DF1LOKpd0662a88acafe3f7ebf33a8d7107ac08_1663641032654.png"
									alt="">
							</view>
							<img class="img-item" :src="item" alt="">
						</view>

					</view>
				</view>
				<!-- 	<view class="cardAIWp">
					<view class="cardAI" @click="">
						AI名片识别
					</view>
					<view class="">
						<u-upload accept="image" :fileList="fileListAI" @afterRead="afterReadByAI" @delete="deletePic"
							name="AI" :multiple='false' :maxCount="1" width="150" height="150" imageMode="aspectFit">
							<image
								src="https://file.casugn.com/storecompcard//M5OoEeK3jlYrdc0867384860ff1cf424406a0bc80d83_1668674475925.png"
								mode="aspectFit" style="width: 150rpx;height: 150rpx;"></image>
						</u-upload>
					</view>
				</view> -->
				<view class="fromWp">
					<u--form labelPosition="left" :model="formData" :rules="rules" ref="form" labelWidth='180'
						labelAlign='left'
						:labelStyle="{marginLeft: '10px',fontSize: '30rpx',color: '#1D2129',height:'96rpx',lineHeight:'96rpx'}"
						:borderBottom="true">
						<view class="paddingWp">
						</view>
						<u-form-item label="头像" class='formItemWp'>
							<view style="display: flex;align-items:center;">
								<view style="flex: 1;color: #c0c4cc;">
									点击图标选择头像
								</view>
								<view class="avatarImgWp">
									<button class="u-reset-button" open-type="chooseAvatar"
										@chooseavatar="onChooseAvatar">
										<img v-if="formData.head!=''" :src="formData.head" alt="" class='avatarImg'>
										<img v-if="formData.head==''"
											src="https://file.casugn.com/storecompcard/temp/general／user@2x(2)_1681184108180.png"
											alt="默认头像" class='defaultAvatarImg'>
									</button>

								</view>
								<view class="">
									<u-icon name="arrow-right" color="#c9cdd4" size="32"></u-icon>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="姓名" prop="name" required borderBottom class='formItemWp'>
							<u--input maxlength="5" v-model="formData.name" border="none" placeholder='请输入姓名(5字内)'>
							</u--input>
						</u-form-item>
						<u-form-item label="公司" prop="company" required borderBottom class='formItemWp'>
							<view style="position: relative;">
								<u--input maxlength="30" v-model.trim="formData.company" border="none"
									@input="inputCompany" placeholder='请输入公司名称(30字内)'>
								</u--input>
								<view class="uni-select__selector" v-if="showSelector">
									<view class="uni-popper__arrow"></view>
									<scroll-view scroll-y="true" class="uni-select__selector-scroll">
										<view class="uni-select__selector-item" v-for="(item,index) in companyList"
											:key="item.id" @click="selectorCompany(item)">
											<text>{{item.company}}</text>
										</view>
									</scroll-view>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="手机号" class='formItemWp' borderBottom>
							<u--input maxlength="11" type="number" v-model="formData.mobile" border="none"
								placeholder='请输入手机号' @blur="phoneInputBlur">
							</u--input>
						</u-form-item>
						<u-form-item label="职位" prop="position" borderBottom class='formItemWp'>
							<u--input maxlength="15" v-model="formData.position" border="none"
								placeholder='请输入职位(15字内)'>
							</u--input>
						</u-form-item>
						<u-form-item label="公司地址" prop="address" class='formItemWp' borderBottom @click='getLocation'>
							<u-input maxlength="40" readonly v-model="formData.address" border="none"
								placeholder='请点击选择公司地址'>
								<template slot="suffix">
									<u-icon name="map" @click='getLocation' color="#c9cdd4" size="36"></u-icon>
								</template>
							</u-input>
						</u-form-item>
						<u-form-item label="邮箱" class='formItemWp' borderBottom>
							<u--input maxlength="20" v-model="formData.mail" border="none" placeholder='请输入邮箱(20字内)'>
							</u--input>
						</u-form-item>
						<u-form-item label="联系方式" class='formItemWp' borderBottom>
							<u--input maxlength="20" type="number" v-model="formData.wechat" border="none"
								placeholder='请输入其他联系方式'>
							</u--input>
						</u-form-item>
					</u--form>



				</view>
			</view>

		</view>
		<view class="submitWp bottomBar">
			<view class="submitBtn">
				<u-button @click="submit" :throttleTime="1000" color="#276aee">创建</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
	} from 'vuex'
	import baseConfig from '@/config/baseUrl.js'
	import defaultCreateCard from '@/components/cardStyle/defaultCreateCard.vue'
	import cardStyle1 from '@/components/cardStyle/cardStyle1.vue'
	import cardStyle2 from '@/components/cardStyle/cardStyle2.vue'
	import cardStyle4 from '@/components/cardStyle/cardStyle4.vue'
	import cardStyle5 from '@/components/cardStyle/cardStyle5.vue'
	import cardStyle6 from '@/components/cardStyle/cardStyle6.vue'
	import defaultCard from '@/components/cardStyle/defaultCard.vue'
	const chooseLocation = requirePlugin('chooseLocation');
	import {
		CardStyleList
	} from '@/config/staticConfig.js'
	export default {
		components: {
			cardStyle1,
			cardStyle2,
			cardStyle4,
			cardStyle5,
			cardStyle6,
			defaultCard
		},
		data() {
			return {
				formData: {
					position: '',
					name: '',
					department: '',
					mobile: '',
					mail: '',
					wechat: '',
					address: '',
					company: '',
					head: '',
				},
				customerTagsVal: "",
				fileListAI: [],
				//上传图片显示
				fileListImg: [],
				rules: {
					// 对name字段进行必填验证
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: ['blur'],
					}, ],
					company: [{
						required: true,
						message: '请输入公司名称',
						trigger: ['blur'],
					}, ],
					address: [{
						required: true,
						message: '请选择公司地址',
						trigger: ['change'],
					}, ],
					// position: [{
					// 	required: true,
					// 	message: '请输入职位',
					// 	trigger: ['blur'],
					// }, ],

				},
				CardStyleList,
				acvtiveIndex: '0',
				openId: '',
				unionId: '',
				companyList: [],
				showSelector: false,
				settimer: null //节流定时器
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad() {
			this.getOpenId()
		},
		onShow() {
			//地图插件选点
			const location = chooseLocation.getLocation();
			if (location != null) {
				// console.log('获取地址信息', location);
				this.formData.address = location.address
				this.formData.coord = JSON.stringify(location) //发送给后台字符串
			}
		},
		onUnload() {
			// 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
			chooseLocation.setLocation(null);
		},
		computed: {
			...mapState(['userInfo']),
		},
		methods: {
			async getOpenId() {
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: async (loginRes) => {
						let code = loginRes.code
						let payload = {
							code
						}
						let res = await this.$api.getOpenIdByCode(payload);
						if (res) {
							this.openId = res.openid
							this.unionId = res.unionid
						} else {
							uni.showToast({
								title: '获取数据失败,请检查网络',
								icon: 'none'
							});
						}
					}
				});
			},
			// 轮播名片切换
			swiperChange(e) {
				console.log(e.detail)
				this.acvtiveIndex = e.detail.current
			},
			// 切换名片样式
			changeCardStyle(item, index) {
				console.log(item, index)
				this.acvtiveIndex = index
			},
			async afterReadByAI(event) {
				uni.showLoading({
					title: '识别中'
				})
				let imageUrl = await this.uploadFilePromise(event.file.url)
				if (imageUrl) {
					let cardInfo = await this.$api.distinguishCardByBaidu({
						imageUrl
					})
					console.log(cardInfo, 'cardInfo');
					if (cardInfo.success) {
						const {
							company,
							email,
							mobile,
							tel,
							name,
							title
						} = cardInfo.result
						console.log(company, email, mobile, tel, name, title);
						this.formData.name = name[0] ? name[0] : ''
						this.formData.mobile = mobile[0] ? mobile[0] : ''
						this.formData.mail = email[0] ? email[0] : ''
						this.formData.company = company[0] ? company[0] : ''
						this.formData.wechat = tel[0] ? tel[0] : ''
						this.formData.position = title[0] ? title[0] : ''
					} else {
						uni.showToast({
							title: cardInfo.message,
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: '上传图片失败',
						icon: 'none'
					});
				}

				uni.hideLoading()

			},
			async onChooseAvatar(e) {
				uni.showLoading({
					title: '上传中'
				})
				const {
					avatarUrl
				} = e.detail
				//上传图片地址
				let imgUrl = await this.uploadFilePromise(avatarUrl)
				console.log(imgUrl, 'imgUrl');
				this.formData.head = imgUrl
				uni.hideLoading()
			},
			getLocation() {
				const key = baseConfig.mapData.mapKey; //使用在腾讯位置服务申请的key
				const referer = baseConfig.mapData.appName //调用插件的app的名称
				const location = ''

				wx.navigateTo({
					url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
				});
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('新增图片', event);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: event.name,
						url: result,
						fileName: event.file[0].type + event.file[0].size + '',
						filePath: result
					}))
					fileListLen++
				}

			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.success) {
								resolve(data.message)
							}
						}
					});
				})
			},
			submit() {
				this.$refs.form.validate().then(res => {
					console.log(res, 'res');
					let payload = {
						address: this.formData.locationInfo,
						...this.formData,
						tempOpenId: this.openId,
						style: this.acvtiveIndex, //名片样式
					}
					this.$api.addCardTemplate(payload).then(res => {
						if (res.success) {
							uni.showToast({
								title: res.message,
								icon: 'none'
							});
							uni.navigateBack()
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							});
						}

					})
				}).catch(errors => {
					console.log(errors, 'errors');
					uni.$u.toast('内容填写有误,请修改或补充')
				})
			},
			phoneInputBlur(e) {
				if (!uni.$u.test.mobile(e))
					return uni.showToast({
						icon: 'none',
						title: '请输入正确手机号'
					})

			},
			inputCompany(e) {
				if (e !== '') {
					if (this.settimer) {
						clearTimeout(this.settimer)
					}
					this.settimer = setTimeout(async () => {
						let payload = {
							company: `*${e}*`,
							status: 1
						}
						let res = await this.$api.queryCompanyExamineList(payload)
						if (res.success && res.result.records) {
							if (res.result.records.length > 0) {
								this.companyList = res.result.records
								this.showSelector = true
							} else {
								this.formData.company = e
								this.companyList = []
								this.showSelector = false
							}
						}
					}, 400)
				} else {
					this.formData.company = ''
					this.companyList = []
					this.showSelector = false
				}
			},
			selectorCompany(item) {
				console.log(item);
				this.formData.company = item.company
				this.formData.companyId = item.id
				this.showSelector = false
			}


		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-upload__deletable {
		right: 20upx;
		top: 20upx;
		width: 20upx;
		height: 20upx;
		text-align: center;
		border-bottom-left-radius: 0;

		// background: transparent;
		.u-icon--right {
			text {
				font-size: 30upx !important;
				top: 6upx !important;
				left: 6upx !important;
			}
		}
	}

	.createCardWp {
		padding-bottom: 200rpx;
	}



	/* picker 弹出层通用的指示小三角 */
	.uni-popper__arrow,
	.uni-popper__arrow::after {
		position: absolute;
		display: block;
		width: 0;
		height: 0;
		border-color: transparent;
		border-style: solid;
		border-width: 6px;
	}

	.uni-popper__arrow {
		filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
		top: -6px;
		left: 10%;
		margin-right: 3px;
		border-top-width: 0;
		border-bottom-color: #EBEEF5;
	}

	.uni-popper__arrow::after {
		content: " ";
		top: 1px;
		margin-left: -6px;
		border-top-width: 0;
		border-bottom-color: #fff;
	}

	.uni-select__selector {

		/* #ifndef APP-NVUE */
		box-sizing: border-box;
		/* #endif */
		position: absolute;
		top: calc(100% + 20rpx);
		left: 0;
		width: 100%;
		background-color: #ffffff;
		border: 1px solid #EBEEF5;
		border-radius: 6px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		z-index: 999;
		padding: 4px 0;
	}

	.uni-select__selector-scroll {
		/* #ifndef APP-NVUE */
		max-height: 200px;
		box-sizing: border-box;
		/* #endif */
	}

	.uni-select__selector-empty,
	.uni-select__selector-item {
		/* #ifndef APP-NVUE */
		display: flex;
		cursor: pointer;
		/* #endif */
		line-height: 35px;
		font-size: 14px;
		text-align: center;
		/* border-bottom: solid 1px $uni-border-3; */
		padding: 0px 10px;
	}

	.uni-select__selector-item:hover {
		background-color: #f9f9f9;
	}

	.uni-select__selector-empty:last-child,
	.uni-select__selector-item:last-child {
		/* #ifndef APP-NVUE */
		border-bottom: none;
		/* #endif */
	}

	// 弹窗结束
	.swiper-top {
		.swiper {
			height: 448rpx;
		}

		.item-swiper {

			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.submitWp {
		z-index: 9999;
		height: 180rpx;
		width: 100%;
		background-color: #fff;
		position: fixed;
		bottom: 10rpx;

		box-sizing: border-box;



		.submitBtn {
			margin: 30rpx 50rpx;
		}
	}


	.cardFrom {
		padding: 0 30upx;

		.cardAIWp {
			display: flex;
			justify-content: space-evenly;
			align-items: center;

			.cardAI {
				flex: 1;
				color: #005ec0;
				font-size: 40rpx;
				letter-spacing: 10rpx;
				font-weight: bolder;
			}
		}

		.titleText {
			font-size: 30upx;
			line-height: 96rpx;

			font-weight: 600;
		}

		.position {


			.titleText {
				height: 96rpx;
				font-size: 30upx;
				font-weight: 600;
				line-height: 96rpx;
			}

			.img-list-box {
				margin-top: 20upx;
				display: flex;
				overflow-x: scroll;

				.img-list-item {
					display: inline-block;
					position: relative;
					margin-left: 20upx;
					border-radius: 10upx;

					.img-list-mask {
						position: absolute;
						width: 100%;
						height: 100%;
						top: 0;
						left: 0;

						background: rgba(0, 0, 0, 0.5);
						text-align: center;

						img {
							width: 50upx;
							height: 50upx;
							position: relative;
							top: 50%;
							transform: translateY(-25upx);
						}
					}

					.img-item {
						width: 140upx;
						height: 100upx;

					}
				}

			}


		}

		.fromWp {
			.avatarImgWp {
				margin-right: 16rpx;
				background-color: #c9cdd4;
				width: 80rpx;
				height: 80rpx;

				.defaultAvatarImg {
					margin-top: 15rpx;
					border-radius: 4rpx;
					width: 50rpx;
					height: 50rpx;
				}

				.avatarImg {
					border-radius: 4rpx;
					width: 80rpx;
					height: 80rpx;
				}

			}

			//
			.formItemWp {
				margin: 0 50upx;
				height: 108rpx;
				border-bottom: #666;
			}

			.paddingWp {
				margin-top: 40upx;
				width: 750rpx;
				height: 20upx;
				margin-left: -30rpx;
				background-color: #F8F9FF;
			}

			.uploadWp {
				border: 1px dotted #423CFE
			}

			// 个人标签
			.personInfoTagWp {
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				.tagItemWp {
					margin-right: 14upx;
					margin-bottom: 20upx;
				}
			}




			.introductionWp {
				margin: 0 20upx;

				.introductionposition {
					margin: 40upx 0;
					font-size: 30upx;
					font-weight: 600;
					color: #000000;
					line-height: 36upx;

					.tagsTitle2 {
						font-size: 24rpx;
						color: #666;
						padding-left: 10upx;
					}
				}

			}
		}
	}

	::v-deep .u-form-item__body__left__content__label {
		font-weight: 600 !important;
	}
</style>
